<template>
  <div class="forum-index">
    <!-- 论坛头部 -->
    <div class="forum-header">
      <h1 class="forum-title">社区论坛</h1>
      <div class="header-actions">
        <div class="search-box">
          <input type="text" placeholder="搜索内容" v-model="searchQuery" @keyup.enter="handleSearch">
          <button class="search-btn" @click="handleSearch">
            🔍 搜索内容
          </button>
        </div>
        <button class="post-btn" @click="handleNewPost">
          + 发帖
        </button>
      </div>
    </div>

    <!-- 分类标签 -->
    <div class="category-tabs">
      <button v-for="category in categories" :key="category.id"
        :class="['tab-btn', { active: activeCategory === category.id }]" @click="setActiveCategory(category.id)">
        {{ category.name }}
      </button>
    </div>

    <!-- 排序选项 -->
    <div class="sort-tabs">
      <button v-for="sort in sortOptions" :key="sort.id" :class="['sort-btn', { active: activeSort === sort.id }]"
        @click="setActiveSort(sort.id)">
        {{ sort.name }}
      </button>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-list">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载帖子...</p>
      </div>
      
      <!-- 无数据状态 -->
      <div v-else-if="filteredPosts.length === 0" class="empty-container">
        <p>暂无帖子</p>
      </div>
      
      <!-- 帖子列表 -->
      <div v-else v-for="post in filteredPosts" :key="post.id" class="post-item" @click="viewPost(post.id)">
        <div class="post-header">
          <div class="user-info">
            <div class="avatar">
              <img v-if="post.author.avatar" :src="post.author.avatar" :alt="post.author.name" class="avatar-img">
              <img v-else src="@/assets/touxiang.png" alt="默认头像" class="avatar-img">
            </div>
            <div class="user-details">
              <div class="username-row">
                <span class="username">{{ post.author.name }}</span>
                <RoleBadge :roles="post.author.roles" />
              </div>
              <span class="post-time">{{ post.createdAt }}</span>
            </div>
          </div>
          <div class="post-tags">
            <span v-for="tag in post.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
        </div>

        <div class="post-content">
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-preview">{{ post.preview }}</p>

          <!-- 图片预览 - 最多显示3张 -->
          <div v-if="post.imageList && post.imageList.length > 0" class="post-images" 
               :class="{ 'single-image': post.imageList.length === 1, 'two-images': post.imageList.length === 2 }">
            <div v-for="(image, index) in post.imageList.slice(0, 3)" 
                 :key="index" 
                 class="image-wrapper"
                 @click.stop="previewImage(image)">
              <img :src="image" :alt="`图片${index + 1}`" class="preview-image">
              <div v-if="index === 2 && post.imageList.length > 3" class="image-more-overlay">
                +{{ post.imageList.length - 3 }}
              </div>
            </div>
          </div>
        </div>

        <div class="post-stats">
          <span class="stat-item">
            👁️ {{ post.views }}
          </span>
          <span class="stat-item like-btn" @click.stop="handleLike(post)">
            {{ post.isLiked ? '❤️' : '🤍' }} {{ post.likes }}
          </span>
          <span class="stat-item">
            💬 {{ post.comments }}
          </span>
        </div>
      </div>
    </div>

    <!-- 图片预览弹窗 -->
    <teleport to="body">
      <div v-if="previewImageUrl" class="image-preview-overlay" @click="closePreview">
        <button class="preview-close-btn" @click="closePreview">×</button>
        <img :src="previewImageUrl" class="preview-image-full" @click.stop alt="预览图片">
      </div>
    </teleport>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getForumCategoryPage, getPostPage, togglePostLike } from '@/api/forum'
import { getCurrentUserPermissions } from '@/api/user'
import { useUserStore } from '@/stores/user'
import RoleBadge from '@/components/RoleBadge.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const searchQuery = ref('')
const activeCategory = ref('all')
const activeSort = ref('latest')
const isLoading = ref(true) // 添加加载状态

// 分类数据
const categories = ref([
  { id: 'all', name: '全部' }
])

// 排序选项
const sortOptions = ref([
  { id: 'latest', name: '最新' },
  { id: 'hot', name: '最热' },
  { id: 'featured', name: '精华' }
])

// 帖子数据
const posts = ref([])
const previewImageUrl = ref('') // 预览图片URL

// 计算属性：过滤后的帖子
const filteredPosts = computed(() => {
  let filtered = posts.value

  // 按分类过滤
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(post => post.category === activeCategory.value)
  }

  // 按搜索关键词过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(post =>
      post.title.toLowerCase().includes(query) ||
      post.preview.toLowerCase().includes(query)
    )
  }

  // 按排序方式排序
  switch (activeSort.value) {
    case 'hot':
      filtered.sort((a, b) => (b.views + b.likes + b.comments) - (a.views + a.likes + a.comments))
      break
    case 'featured':
      filtered.sort((a, b) => {
        const aFeatured = a.tags.includes('精华') ? 1 : 0
        const bFeatured = b.tags.includes('精华') ? 1 : 0
        return bFeatured - aFeatured
      })
      break
    default: // latest
      filtered.sort((a, b) => b.id - a.id)
  }

  return filtered
})

// 方法
const handleSearch = () => {
  console.log('搜索:', searchQuery.value)
}

const handleNewPost = async () => {
  // 检查用户是否已登录
  if (!userStore.uid) {
    alert('请先登录')
    router.push('/user/login')
    return
  }
  
  // 在跳转到发帖页面前，先获取用户权限
  try {
    const permissionRes = await getCurrentUserPermissions(userStore.uid)
    if (permissionRes.code === 200 && permissionRes.data && permissionRes.data.roleList) {
      userStore.setUserRoles(permissionRes.data.roleList)
    }
  } catch (error) {
    console.error('获取用户权限失败:', error)
  }
  
  // 跳转到发帖页面
  router.push('/forum/create')
}

const setActiveCategory = (categoryId) => {
  activeCategory.value = categoryId
}

const setActiveSort = (sortId) => {
  activeSort.value = sortId
}

const viewPost = (postId) => {
  router.push(`/forum/post/${postId}`)
}

// 图片预览功能
const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  document.body.style.overflow = 'hidden'
}

// 关闭预览
const closePreview = () => {
  previewImageUrl.value = ''
  document.body.style.overflow = ''
}

// 点赞或取消点赞
const handleLike = async (post) => {
  // 检查用户是否已登录
  if (!userStore.uid) {
    alert('请先登录')
    return
  }

  try {
    // 调用点赞接口
    const res = await togglePostLike(post.id, userStore.uid)
    
    console.log('点赞接口返回:', res)

    // 根据接口返回的数据更新状态
    if (res.code === 200 && res.data) {
      // 更新点赞状态
      post.isLiked = res.data.liked
      
      // 更新点赞数
      post.likes = res.data.count
      
      console.log(`帖子 ${post.id} 点赞状态已更新: liked=${res.data.liked}, count=${res.data.count}`)
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    alert('点赞操作失败，请稍后重试')
  }
}

// 获取帖子分页数据
const fetchPosts = async () => {
  try {
    const params = {
      pageNo: 1,
      pageSize: 10
    }

    // 如果不是"全部"分类，则添加categoryId参数
    if (activeCategory.value !== 'all') {
      params.categoryId = activeCategory.value
    }

    console.log('正在获取帖子数据，参数:', params)
    const res = await getPostPage(params)
    console.log('获取帖子数据成功:', res)

    // 如果接口返回成功，更新帖子数据
    if (res.code === 200 && res.data && res.data.list) {
      // 将API返回的数据转换为前端所需格式
      const apiPosts = res.data.list.map(item => ({
        id: item.id,
        userId: item.userId,
        author: {
          name: item.users?.nickName || item.authorName || '匿名用户',
          avatar: item.users?.avatar || '', // 完整的头像URL
          avatarText: item.users?.nickName ? item.users.nickName.substring(0, 2) : '匿', // 头像文字
          badge: item.authorBadge || '',
          roles: [] // 初始化角色数组
        },
        createdAt: item.createTime || '未知时间',
        tags: item.tags || [],
        title: item.title || '无标题',
        preview: item.content ? item.content.substring(0, 100) + '...' : '无内容',
        views: item.viewCount || 0,
        likes: item.likeCount || 0,
        comments: item.commentCount || 0,
        category: item.categoryId ? item.categoryId.toString() : 'all',
        images: item.images || [],
        imageList: item.imageList || [], // 添加imageList字段
        isLiked: item.liked || false // 从接口读取点赞状态
      }))

      posts.value = apiPosts
      
      // 获取每个帖子作者的角色信息
      for (const post of posts.value) {
        if (post.userId) {
          try {
            const permissionRes = await getCurrentUserPermissions(post.userId)
            if (permissionRes.code === 200 && permissionRes.data && permissionRes.data.roleList) {
              post.author.roles = permissionRes.data.roleList
            }
          } catch (error) {
            console.error(`获取用户${post.userId}权限失败:`, error)
          }
        }
      }
    }
  } catch (error) {
    console.error('获取帖子数据失败:', error)
  } finally {
    // 无论成功还是失败，都设置加载状态为false
    isLoading.value = false
  }
}

// 监听分类变化，重新获取帖子数据
watch(activeCategory, () => {
  isLoading.value = true // 切换分类时显示加载状态
  fetchPosts()
})

onMounted(async () => {
  console.log('论坛页面已加载')
  console.log('当前 token:', userStore.token)

  // 获取帖子分类
  try {
    const res = await getForumCategoryPage()
    console.log('获取帖子分类成功:', res)

    // 如果接口返回成功，更新分类数据
    if (res.code === 200 && res.data && res.data.list) {
      // 保留"全部"选项，添加从接口获取的分类
      const apiCategories = res.data.list.map(item => ({
        id: item.id.toString(),
        name: item.categoryName
      }))

      categories.value = [
        { id: 'all', name: '全部' },
        ...apiCategories
      ]
    }
  } catch (error) {
    console.error('获取帖子分类失败:', error)
  }

  // 获取帖子数据
  fetchPosts()
})
</script>

<style scoped>
.forum-index {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 论坛头部 */
.forum-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.forum-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-box {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 20px;
  padding: 5px;
}

.search-box input {
  border: none;
  background: transparent;
  padding: 8px 15px;
  outline: none;
  width: 200px;
}

.search-btn {
  background: #ff9500;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 15px;
  cursor: pointer;
  font-size: 14px;
}

.post-btn {
  background: #4285f4;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
  font-weight: bold;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  overflow-x: auto;
  padding: 5px 0;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
}

.category-tabs::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari and Opera */
}

.tab-btn {
  background: white;
  border: 1px solid #e0e0e0;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  color: #666;
  transition: all 0.3s;
  white-space: nowrap;
  flex-shrink: 0;
}

.tab-btn.active {
  background: #4285f4;
  color: white;
  border-color: #4285f4;
}

.tab-btn:hover {
  background: #f0f0f0;
}

.tab-btn.active:hover {
  background: #4285f4;
}

/* 排序选项 */
.sort-tabs {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding-left: 10px;
}

.sort-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 16px;
  padding: 5px 0;
  position: relative;
}

.sort-btn.active {
  color: #4285f4;
  font-weight: bold;
}

.sort-btn.active::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  right: 0;
  height: 2px;
  background: #4285f4;
}

/* 帖子列表 */
.posts-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4285f4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 无数据状态 */
.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  color: #999;
}

.post-item {
  background: white;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.post-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username-row {
  display: flex;
  align-items: center;
  gap: 4px;
}

.username {
  font-weight: bold;
  color: #333;
}

.user-badge {
  background: #ff69b4;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  align-self: flex-start;
}

.post-time {
  color: #999;
  font-size: 12px;
}

.post-tags {
  display: flex;
  gap: 5px;
}

.tag {
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.post-content {
  margin-bottom: 15px;
}

.post-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.post-preview {
  color: #666;
  line-height: 1.5;
  margin: 0 0 10px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 图片展示区域 */
.post-images {
  display: grid;
  gap: 6px;
  margin-top: 12px;
  grid-template-columns: repeat(3, 1fr);
}

.post-images.single-image {
  grid-template-columns: 1fr;
}

.post-images.single-image .image-wrapper {
  max-height: 200px;
}

.post-images.two-images {
  grid-template-columns: repeat(2, 1fr);
}

.image-wrapper {
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* 1:1 宽高比 */
  overflow: hidden;
  border-radius: 8px;
  background: #f5f5f5;
  cursor: pointer;
  transition: all 0.2s;
}

.image-wrapper:hover {
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.preview-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-more-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  font-weight: bold;
}

/* 图片预览弹窗样式 */
.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 60px 20px 20px;
  box-sizing: border-box;
}

.preview-image-full {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
  border-radius: 8px;
}

.preview-close-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 44px;
  height: 44px;
  background-color: rgba(255, 255, 255, 0.95);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  line-height: 1;
  font-weight: normal;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
  z-index: 10000;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.preview-close-btn:active {
  background-color: #fff;
  transform: scale(0.9);
}

.post-stats {
  display: flex;
  gap: 15px;
  color: #999;
  font-size: 14px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.like-btn {
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
}

.like-btn:hover {
  transform: scale(1.1);
  color: #ff4757;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .forum-index {
    padding: 10px;
  }

  .forum-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: space-between;
  }

  .search-box input {
    width: 150px;
  }

  .category-tabs {
    margin: 0 -10px 15px -10px;
    padding: 5px 10px;
  }

  .post-header {
    flex-direction: column;
    gap: 10px;
  }

  .post-tags {
    align-self: flex-start;
  }
}

@media (max-width: 480px) {
  .forum-header {
    padding: 10px 15px;
  }

  .search-box input {
    width: 120px;
  }

  .search-btn,
  .post-btn {
    padding: 8px 12px;
    font-size: 12px;
  }

  .post-item {
    padding: 12px;
  }

  .post-title {
    font-size: 15px;
  }

  .post-preview {
    font-size: 14px;
  }
}
</style>